import { ref } from "vue";

interface RegisterUser {
  name: string;
  email: string;
  password: string;
  password2: string;
  role: string;
}

interface RegisterRules {
  name: ({
    message: string;
    required: boolean;
    trigger: string;
  } | {
    min: number;
    max: number;
    message: string;
    trigger: string;
  })[];
  email: {
    type: string;
    message: string;
    required: boolean;
    trigger: string;
  }[];
  password: ({
    required: boolean;
    message: string;
    trigger: string;
  } | {
    min: number;
    max: number;
    message: string;
    trigger: string;
  })[];
  password2: ({
    required: boolean;
    message: string;
    trigger: string;

  } | {
    min: number;
    max: number;
    message: string;
    trigger: string;

  } | {
    validator: (rule: RegisterRules, value: string, callback: any) => void;
    trigger: string;
  })[];
}

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== registerUser.value.password) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};

export const registerUser = ref<RegisterUser>({
  name: "",
  email: "",
  password: "",
  password2: "",
  role: ""
})

export const registerRules = ref({
  name: [
    { message: "请输入用户名", required: true, trigger: 'blur' },
    { min: 2, max: 15, message: "长度在2-15之间", trigger: 'blur' }
  ],
  email: [
    { type: "email", message: "请输入正确的邮箱地址", required: true, trigger: 'blur' }
  ],
  password: [
    { message: "密码不能为空", required: true, trigger: 'blur' },
    { min: 6, max: 30,  message: "密码长度在6-30之间", trigger: 'blur' }
  ],
  password2: [
    { message: "密码不能为空", required: true, trigger: 'blur' },
    { min: 6, max: 30,  message: "密码长度在6-30之间", trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ]
})